import React, { useState } from 'react';
import cx from 'classnames';
import S from './index.m.less';

// 滚动动画
function animateScroll(dom, targetLeft, time = 200) {
    let currentLeft = $(dom).scrollLeft();
    const maxTime = time / 10;
    const PER = (targetLeft - currentLeft) / maxTime;
    let execTime = 1;

    const interval = setInterval(() => {
        currentLeft += PER;
        $(dom).scrollLeft(currentLeft);
        execTime += 1;
        if (execTime > maxTime) {
            window.clearInterval(interval);
        }
    }, 10);
    return interval;
}

export default function SlideWrap(props) {
    const {
        renderItem, current, renderItemClick, menu, className
    } = props;

    const [selected, setSelected] = useState(current || 0); // 默认选中
    const [time] = useState(200); // 动画时间

    const scrollNavigation = (item, i) => {
        const ele = document.querySelectorAll('.catwrap-item')[i];
        const wrapEle = document.getElementsByClassName('catWrap')[0];
        const scrollEle = wrapEle.parentElement;

        if (!ele || !wrapEle) return;
        const { offsetLeft: eleLeft, offsetWidth: eleWidth } = ele;
        const { clientWidth: wrapWidth } = scrollEle;

        // 居中选择项
        // 容器滚动条左边距离 + 容器宽度1/2 == 元素左边距 + 元素宽度1/2
        const targetScrollLeft = eleLeft + eleWidth / 2 - wrapWidth / 3;
        animateScroll(scrollEle, targetScrollLeft, time);
    };

    const anchor = (item, i) => {
        if (selected == item) return;
        setSelected(item);
        scrollNavigation(item, i);
        renderItemClick(item, i);
    };

    // useEffect(() => {
    //     renderItemClick();
    // }, [selected])

    return (
        <div className={cx(S.menuWrap, className)}>
            <ul className={cx(S.catwrap, 'catWrap')}>
                {menu.map((item, i) => (
                    <li key={i} className={cx(S.item, 'catwrap-item')} onClick={() => anchor(item, i)}>
                        {renderItem()}
                    </li>
                ))}
            </ul>
        </div>
    );
}
